package com.haliyoo.adhere.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.bean.UserBean;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.AdUserConstant;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.sqlite.DataHelper4User;
import com.haliyoo.adhere.util.DateUtilsDef;
import com.haliyoo.adhere.widget.WeiboLayout;

import weibo4android.Count;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CreativeHallActivity extends Activity {
	private static String TAG = "CreativeHallActivity";
	private static final int WEIBO_SET_HALL = 1;
	private static final int WEIBO_SET_CHARM_CREATIVE = 2;
	private static final int WEIBO_SET_CHARM_CHARM = 3;
	private static final int WEIBO_SET_CHARM_CONTRIBUTIONS = 4;
	private static final int WEIBO_SET_CHARM_COLLEAGUES = 5;
	private WeiboList weiboList = null;
	private static User user = null;
	public static Weibo weibo = null;
	private GetUserThread getUserThread = null;

	/**
	 * 内部类，实现微博数据获取
	 * @author wation.haliyoo
	 *
	 */
	class WeiboList extends WeiboLayout{
		private int weiboSet = 0;

		@Override
		public List<WeiboBean> onGetNewWeiboList() {
			// TODO Auto-generated method stub
			if (LoginActivity.getUser() == null) {
				Toast.makeText(CreativeHallActivity.this, 
						R.string.STR_NONE_USER, 
						Toast.LENGTH_SHORT).show();
			} else {
				List<WeiboBean> wbList = new ArrayList<WeiboBean>();

				try {
					Weibo weibo = OAuthConstant.getInstance().getWeibo();
					
					weibo.setToken(OAuthConstant.getInstance().getToken(), 
							OAuthConstant.getInstance().getTokenSecret());
					
					List<Status> weiboList = null;

					weiboList = getWeiboList(weibo, weiboSet);
					
					/// 清空原有list所有项
					wbList.clear();
					
					if (weiboList == null) {
						return null;
					}
					
					for (Status status : weiboList) {
						WeiboBean wb = new WeiboBean();
						
						/// 标识
						wb.setWeiboId(status.getId());
						
						/// 头像
						//wb.setProfile(BitmapGet.getHttpBitmap(status.getUser().getProfileImageURL()));
						wb.setProfileUrl(status.getUser().getProfileImageURL().toString());
						
						/// 用户名
						wb.setUser(status.getUser().getScreenName());
						
						/// 微博
						wb.setText(status.getText());
						
						/// 时间
						wb.setTime(status.getCreatedAt());
						Date startDate = status.getCreatedAt();
						Date nowDate = Calendar.getInstance().getTime();
						String timeDifferenceStr = new DateUtilsDef(CreativeHallActivity.this).twoDateDistance(
								startDate, nowDate);
						wb.setTimeDifference(timeDifferenceStr + getString(R.string.STR_AGO));
						
						/// 是否包含图片
						if (status.getThumbnail_pic() == null || status.getThumbnail_pic().equals("")){
							wb.setExistImage(false);
						} else {
							wb.setIconUrl(status.getOriginal_pic());
							wb.setExistImage(true);
						}
						
						/// 是否包含定位信息
						if (status.getLatitude() > 0.0 && status.getLongitude() > 0.0) {
							wb.setExistLocation(true);
							wb.setLatitude(status.getLatitude());
							wb.setLongitude(status.getLongitude());
						} else {
							wb.setExistLocation(false);
						}
						
						/// 是否为转发的
						if (status.isRetweet()) {
							WeiboBean retweet = new WeiboBean();
							Status retweetStatus = status.getRetweeted_status();
							
							retweet.setUser(retweetStatus.getUser().getScreenName());
							retweet.setText(retweetStatus.getText());
							
							/// 是否包含图片
							if (retweetStatus.getThumbnail_pic() == null || retweetStatus.getThumbnail_pic().equals("")){
								retweet.setExistImage(false);
							} else {
								retweet.setIconUrl(retweetStatus.getOriginal_pic());
								retweet.setExistImage(true);
							}
							
							/// 获取转发原微博的转发数和评论数
							List<Count> counts = weibo.getCounts(new Long(retweetStatus.getId()).toString());

							if (counts != null && counts.size() > 0) {
								Count count = counts.get(0);
								
								Log.i(TAG, "count: " + count.toString());
								
								retweet.setRepostCount((int) count.getRt());
								retweet.setCommentCount((int) count.getComments());
							} else {
								retweet.setRepostCount(0);
								retweet.setCommentCount(0);
							}
							
							wb.setRetweet(retweet);
							
						}

						/// 获取转发原微博的转发数和评论数
						List<Count> counts = weibo.getCounts(new Long(status.getId()).toString());
						
						if (counts != null && counts.size() > 0) {
							Count count = counts.get(0);
							
							Log.i(TAG, "count: " + count.toString());
							
							wb.setRepostCount((int) count.getRt());
							wb.setCommentCount((int) count.getComments());
						} else {
							wb.setRepostCount(0);
							wb.setCommentCount(0);
						}
						
						/// 获取来源
						String source = status.getSource();
						wb.setComeString(AdUserConstant.getSourceByXml(source));
						
						wbList.add(wb);
					}
					
					return wbList;
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return null;
		}
		
		private List<Status> getWeiboList(Weibo weibo, int weiboSet) {
			// TODO Auto-generated method stub

			//friendsTimeline = weibo.getUserTimeline();
			//friendsTimeline = weibo.getHomeTimeline();
			//friendsTimeline = weibo.getFriendsTimeline();
			//friendsTimeline = weibo.getrepostbyme(new Long(LoginActivity.getUser().getUserId()).toString());
			//friendsTimeline = weibo.getMentions();
			//friendsTimeline = weibo.getRetweetsOfMe();
			//friendsTimeline = weibo.getRetweetedToMe();
			//friendsTimeline = weibo.getPublicTimeline(30, 0);
			try {
				Log.i(TAG, "weiboSet: " + weiboSet);
				
				switch (weiboSet) {
				case WEIBO_SET_HALL:
					return weibo.getFriendsTimeline();
					
				/// 显示我发表的微博
				case WEIBO_SET_CHARM_CREATIVE:
					return weibo.getUserTimeline();
					
				/// 显示别人转发的我的微博
				case WEIBO_SET_CHARM_CHARM:
					return weibo.getrepostbyme(LoginActivity.getUser().getId());
					
				/// 显示我转发的微博
				case WEIBO_SET_CHARM_CONTRIBUTIONS:
					return weibo.getrepostbyme(LoginActivity.getUser().getId());
					
				/// 显示好友列表
				case WEIBO_SET_CHARM_COLLEAGUES:
					break;
					
				default:return null;
				}
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		WeiboList(Context context, LinearLayout llWeiboList, int weiboSet) {
			super(context, llWeiboList);
			// TODO Auto-generated constructor stub
			this.weiboSet = weiboSet;
		}

		@Override
		public void onShowWeiboDetail(AdapterView<?> arg0, View view, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Object obj = view.getTag();
			if (obj != null) {
				long id = (Long) obj;
				Intent intent = new Intent(CreativeHallActivity.this,
						CreativeActivity.class);
				Bundle b = new Bundle();
				b.putLong("key", id);
				intent.putExtras(b);
				CreativeHallActivity.this.startActivity(intent);
			}
		}

		@Override
		public void onStartRefresh() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStopRefresh() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public List<WeiboBean> onGetOldWeiboList() {
			// TODO Auto-generated method stub
			return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.creative_hall);
		
		/**
		 * 返回键处理
		 */
		ImageButton ibBack = (ImageButton) findViewById(R.id.IMAGE_BUTTON_BACK);
		ibBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();  
			}
		});

		/**
		 * 写微博键处理
		 */
		ImageButton ibWrite = (ImageButton) findViewById(R.id.IMAGE_BUTTON_WRITE);
		ibWrite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CreativeHallActivity.this,
						CreativeDesignActivity.class);
				startActivity(intent);
			}
		});
		
        TextView tvTitle = (TextView) findViewById(R.id.TEXT_VIEW_TITLE);
        /// 需要展示的是哪一类微博
        int weiboSet = 0;
		
		/// 获取传送过来的消息
        Intent i = this.getIntent();
        AccessToken accessToken = null;
        if (!i.equals(null)){
        	String from = i.getStringExtra("from");
        	
        	/// 从我的魅力页面过来的
            if(from.equals("MyCharmActivity")) {
                String item = i.getStringExtra("item");
                
                /// 我的创意项过来的
                if (item.equals("my creative")) {
                	weiboSet = WEIBO_SET_CHARM_CREATIVE;
                } 
                /// 我的魅力项过来的
                else if (item.equals("my charm")) {
                	weiboSet = WEIBO_SET_CHARM_CHARM;
                }
                /// 我的贡献项过来的
                else if (item.equals("my contributions")) {
                	weiboSet = WEIBO_SET_CHARM_CONTRIBUTIONS;
                }
                /// 我的童鞋项过来的
                else if (item.equals("my colleagues")) {
                	weiboSet = WEIBO_SET_CHARM_COLLEAGUES;
                }
            }  
            /// 从登录页面过来的
            else if (from.equals("LoginActivity")) {

        		Bundle bundle = i.getExtras();
        		
        		/**
        		 * 判断能否获取到bundle，如果获取不到则通过请求获取accessToken
        		 * 否则，直接提取accessToken
        		 */
        		if (bundle != null) {
        			accessToken = (AccessToken) bundle.getSerializable("accesToken");
        		}
        		
            	weiboSet = WEIBO_SET_HALL;
            } else {
    			Uri uri = i.getData();
    			RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
    			try {
    				accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
    				UserBean user = LoginActivity.getUser();
    				
    				/// 保存数据库
    				user.setUserId(accessToken.getUserId());
    				user.setToken(accessToken.getToken());
    				user.setTokenSecret(accessToken.getTokenSecret());
    		    	DataHelper4User dbHelper = new DataHelper4User(this);
    		        dbHelper.insert(user);
    			} catch (WeiboException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
            }
            
            if (accessToken != null) {

        		/**
        		 * 开启线程获取用户信息
        		 */
        		if (getUserThread == null) {
        			getUserThread = new GetUserThread(accessToken);
        		}
        		getUserThread.start();
            }
            
            String title = i.getStringExtra("title");
            tvTitle.setText(title);
    		/// 设置标题
    		//TextView tvTitle = (TextView) findViewById(R.id.TEXT_VIEW_TITLE);
    		tvTitle.setText(LoginActivity.getUser().getUser());
        }

//		/// 加载微博列表
//        RelativeLayout rlList = (RelativeLayout) findViewById(R.id.RELATIVE_LAYOUT_WEIBO_LIST);
//        if (weiboList == null) {
//        	weiboList = new WeiboList(CreativeHallActivity.this, rlList, weiboSet);
//		}
//    	weiboList.refreshWeiboList();
//    	rlList.setOnTouchListener(touch);
	}

	class GetUserThread extends Thread {
		
		AccessToken accessToken = null;
		
		public GetUserThread(AccessToken accessToken) {
			this.accessToken = accessToken;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (accessToken != null) {
			
				try {
					OAuthConstant.getInstance().setAccessToken(accessToken);
					weibo = OAuthConstant.getInstance().getWeibo();
					
					weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
					
					user = weibo.showUser(accessToken.getUserId() + "");
					
					Log.i(TAG, "user:" + user.toString());
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}
			
			super.run();
		}
	}
	/**
	 * 实现拖拽
	 */
	private OnTouchListener touch = new OnTouchListener() {

		int[] temp = new int[] { 0, 0 };

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int eventaction = event.getAction();

			Log.i("&&&", "onTouchEvent:" + eventaction);
			int x = (int) event.getRawX();

			int y = (int) event.getRawY();

			switch (eventaction) {
			case MotionEvent.ACTION_DOWN: //
				temp[0] = (int) event.getX();
				temp[1] = y - v.getTop();

				break;
			case MotionEvent.ACTION_MOVE: // touch drag with the ball
				v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0],
						y - temp[1] + v.getHeight());
				v.postInvalidate();
				break;

			case MotionEvent.ACTION_UP:
				break;
			}

			return false;
		}
	};
	
	public static User getUser() {
		// TODO Auto-generated method stub
		return user;
	}
}
